<?php

namespace app\admin\model\chase;

use app\admin\model\chase\DesignService as DesignServiceModel;
use think\Model;


class DesignService extends Model
{

    

    

    // 表名
    protected $table = 'design_services';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'online_text'
    ];
    

    
    public function getOnlineList()
    {
        return ['no' => __('Online no'), 'yes' => __('Online yes')];
    }


    public function getOnlineTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['online']) ? $data['online'] : '');
        $list = $this->getOnlineList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function design()
    {
        return $this->hasOne(Design::class, 'id', 'design_id');
    }

    public function service()
    {
        return $this->hasOne(ModelingService::class, 'id', 'service_id');
    }

    public static function createService($design_id, $service, $service_prices, $line_prices)
    {
        $data = [];
        foreach ($service as $val) {
            $data[] = [
                'design_id' => $design_id,
                'service_id' => $val,
                'price' => $service_prices[$val],
                'line_price' => $line_prices[$val],
                'createtime' => time(),
                'updatetime' => time()
            ];
        }
        return self::insertAll($data);
    }

    public static function updateService($design_id, $service_ids, $service_prices, $line_prices)
    {
        self::where('design_id', $design_id)->update(['online' => 'no']);
        if ($service_ids[0]) {
            $service_id = self::where('design_id', $design_id)->column('service_id');
            foreach ($service_ids as $val) {
                if (in_array($val, $service_id)) {
                    $design_service = self::where('design_id', $design_id)->where('service_id', $val)->update([
                        'price' => $service_prices[$val],
                        'line_price' => $line_prices[$val],
                        'online' => 'yes'
                    ]);
                } else {
                    self::create([
                        'design_id' => $design_id,
                        'service_id' => $val,
                        'price' => $service_prices[$val],
                        'line_price' => $line_prices[$val]
                    ]);
                }
            }
        }

    }

    public static function getService($design_id)
    {
        return self::with('service')->where('design_id', $design_id)->where('online', 'yes')->select();
    }

}
